package cih;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cci.CtrlInterno;
import cci.CtrlPrincipal;
import cdp.Pessoa;
import cdp.Usuario;

@WebServlet(name = "PagAlterarCadastro", urlPatterns = {"/PagAlterarCadastro"})
public class PagAlterarCadastro extends HttpServlet{
	private CtrlInterno ctrl = CtrlInterno.getInstance();
	
	HttpServletRequest request;
	HttpServletResponse response;
	RequestDispatcher dispatcher;
	HttpSession session;

	private String opcao;
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
		
		this.opcao = (String) request.getParameter("opcao");
		
		this.verificaOperacao();
    }
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {   
        processRequest(request, response);
    }
	
	protected void verificaOperacao()
	{
		if (opcao == null)
		{
			//erro
		}
		else
		{			
			System.out.println("Entrou no else");
			switch(opcao)
			{
				case "voltar": this.voltar(); break;
				case "salvar": this.alterarPessoa(); break;
				
				default: break;
			}
		}
	}
	
	public boolean vericaSenhaAntiga()
	{
		Usuario u = (Usuario) session.getAttribute("usuario");
		String senhaAntiga = (String) request.getParameter("senhaAntiga");
		
		String s = Usuario.gerarHashCode(senhaAntiga);
		
		if(s.equals(u.getSenha()))
		{
			return true;
		}
		
		return false;
	}
	
	private void alterarPessoa()
	{	
		Usuario u = (Usuario) session.getAttribute("usuario");
		Pessoa p = ctrl.obterPessoa(u);
		
		String senha = (String) request.getParameter("senha");
		String confirmacaoSenha = (String) request.getParameter("confirmacaoSenha");

		p.setNome(request.getParameter("nome"));
		p.setEmail(request.getParameter("eMail"));
		p.getUsuario().setSenhaCriptografar(request.getParameter("senha"));
		p.getUsuario().setNome(p.getEmail());
		
		ctrl.alterarPessoa(p);
		
		try {
			response.sendRedirect("PagPrincipal.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void voltar()
	{
		try {
			response.sendRedirect("PagPrincipal.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
